<template>
  <div class="video-card">
    <div class="card-header">
      <h3 class="video-title" :title="video.name">{{ video.name }}</h3>
      <div class="header-actions">
        <button 
          @click="togglePlay" 
          class="control-btn"
          :title="isPlaying ? '暂停' : '播放'"
        >
          <svg v-if="!isPlaying" viewBox="0 0 24 24" fill="currentColor">
            <path d="M8 5v14l11-7z"/>
          </svg>
          <svg v-else viewBox="0 0 24 24" fill="currentColor">
            <path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/>
          </svg>
        </button>
        <button 
          @click="stopVideo" 
          class="control-btn"
          title="停止"
        >
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M6 6h12v12H6z"/>
          </svg>
        </button>
        <button @click="$emit('remove', video.id)" class="remove-btn" title="移除">
          ×
        </button>
      </div>
    </div>
    <div class="video-container">
      <video 
        ref="videoElement" 
        class="video-player"
        controls
        playsinline
        :muted="isMuted"
        @play="handlePlay"
        @pause="handlePause"
        @loadeddata="handleLoadedData"
        @canplay="handleCanPlay"
        @error="handleVideoError"
      >
        您的浏览器不支持视频播放
      </video>
      <div v-if="error" class="error-message">
        <span class="error-icon">⚠️</span>
        <p>{{ error }}</p>
        <button @click="retryLoad" class="retry-btn">重试</button>
      </div>
      <div v-if="loading && !error" class="loading-message">
        <div class="spinner"></div>
        <p>正在加载视频流...</p>
      </div>
      <div v-if="!isPlaying && !loading && !error" class="play-overlay" @click="togglePlay">
        <div class="play-icon">
          <svg viewBox="0 0 24 24" fill="white">
            <path d="M8 5v14l11-7z"/>
          </svg>
        </div>
      </div>
    </div>
    <div class="card-footer">
      <span class="video-url" :title="video.url">{{ video.url }}</span>
      <span class="video-type">{{ videoType }}</span>
      <span v-if="isPlaying" class="status-badge playing">播放中</span>
      <span v-else-if="loading" class="status-badge loading">加载中</span>
      <span v-else class="status-badge stopped">已停止</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import flvjs from 'flv.js'
import Hls from 'hls.js'

const props = defineProps({
  video: {
    type: Object,
    required: true
  },
  maxConcurrent: {
    type: Number,
    default: 6
  }
})

const emit = defineEmits(['remove', 'play-request', 'play-started', 'play-stopped'])

const videoElement = ref(null)
const flvPlayer = ref(null)
const hlsPlayer = ref(null)
const error = ref('')
const loading = ref(true)
const isPlaying = ref(false)
const isMuted = ref(false)
let loadTimeout = null

const videoType = computed(() => {
  const url = props.video.url.toLowerCase()
  if (url.includes('.flv') || url.includes('flv/')) return 'FLV'
  if (url.includes('.m3u8')) return 'M3U8'
  if (url.includes('/hls/')) return 'HLS'
  return 'VIDEO'
})

const getVideoFormat = (url) => {
  const lowerUrl = url.toLowerCase()
  // 优先判断 FLV
  if (lowerUrl.includes('.flv') || lowerUrl.includes('flv/')) {
    return 'flv'
  } else if (lowerUrl.includes('.m3u8') || lowerUrl.includes('/hls/')) {
    return 'hls'
  } else if (lowerUrl.includes('.mp4')) {
    return 'mp4'
  }
  // 如果 URL 包含 flv 关键字，默认使用 FLV
  return lowerUrl.includes('flv') ? 'flv' : 'hls'
}

const handlePlay = () => {
  isPlaying.value = true
  loading.value = false
  emit('play-started', props.video.id)
}

const handlePause = () => {
  isPlaying.value = false
  emit('play-stopped', props.video.id)
}

const handleLoadedData = () => {
  console.log('视频数据已加载:', props.video.name)
  loading.value = false
}

const handleCanPlay = () => {
  console.log('视频可以播放:', props.video.name)
  loading.value = false
}

const togglePlay = async () => {
  if (!videoElement.value) return
  
  try {
    if (isPlaying.value) {
      videoElement.value.pause()
    } else {
      // 检查是否可以播放（是否达到并发限制）
      const canPlay = emit('play-request', props.video.id)
      if (canPlay === false) {
        error.value = `已达到最大同时播放数限制（${props.maxConcurrent}个），请先停止其他视频`
        setTimeout(() => {
          if (error.value.includes('最大同时播放数')) {
            error.value = ''
          }
        }, 3000)
        return
      }
      
      // 首次播放时可能需要用户交互，尝试静音播放
      await videoElement.value.play()
    }
  } catch (err) {
    console.error('播放/暂停失败:', err)
    // 如果播放失败，尝试静音播放
    if (!isPlaying.value) {
      try {
        isMuted.value = true
        await videoElement.value.play()
      } catch (e) {
        error.value = '播放失败，请手动点击播放按钮'
      }
    }
  }
}

const stopVideo = () => {
  if (videoElement.value) {
    videoElement.value.pause()
    videoElement.value.currentTime = 0
    isPlaying.value = false
    emit('play-stopped', props.video.id)
  }
}

// 监听全局停止事件
const handleGlobalStop = () => {
  stopVideo()
}

// 暴露给父组件的方法
const startPlay = () => {
  if (!isPlaying.value && videoElement.value) {
    togglePlay()
  }
}

// 暴露方法
defineExpose({
  startPlay
})

const retryLoad = () => {
  error.value = ''
  loading.value = true
  destroyPlayer()
  setTimeout(() => {
    initPlayer()
  }, 100)
}

const initPlayer = () => {
  if (!videoElement.value) return

  const format = getVideoFormat(props.video.url)
  error.value = ''
  loading.value = true
  
  // 设置超时检测
  if (loadTimeout) clearTimeout(loadTimeout)
  loadTimeout = setTimeout(() => {
    if (loading.value) {
      console.warn('加载超时，但继续尝试播放')
      loading.value = false
    }
  }, 15000) // 15秒超时

  console.log('初始化播放器:', format, props.video.url)

  try {
    if (format === 'flv') {
      initFlvPlayer()
    } else if (format === 'hls') {
      initHlsPlayer()
    } else {
      initNativePlayer()
    }
  } catch (err) {
    console.error('播放器初始化失败:', err)
    error.value = '播放器初始化失败: ' + err.message
    loading.value = false
  }
}

const initFlvPlayer = () => {
  if (!flvjs.isSupported()) {
    error.value = '当前浏览器不支持 FLV 播放'
    loading.value = false
    return
  }

  console.log('使用 FLV.js 播放器')
  
  flvPlayer.value = flvjs.createPlayer({
    type: 'flv',
    url: props.video.url,
    isLive: true,
    hasAudio: true,
    hasVideo: true,
    cors: true
  }, {
    enableWorker: false, // 禁用 Worker 以提高兼容性
    enableStashBuffer: true,
    stashInitialSize: 384, // 增加初始缓冲
    autoCleanupSourceBuffer: true,
    autoCleanupMaxBackwardDuration: 5,
    autoCleanupMinBackwardDuration: 3,
    lazyLoad: false,
    lazyLoadMaxDuration: 3 * 60,
    seekType: 'range',
    reuseRedirectedURL: true
  })

  flvPlayer.value.attachMediaElement(videoElement.value)
  
  flvPlayer.value.on(flvjs.Events.ERROR, (errType, errDetail) => {
    console.error('FLV 播放错误:', errType, errDetail)
    error.value = `FLV 错误: ${errType} - ${errDetail}`
    loading.value = false
    isPlaying.value = false
  })

  flvPlayer.value.on(flvjs.Events.LOADING_COMPLETE, () => {
    console.log('FLV 加载完成')
    loading.value = false
  })

  flvPlayer.value.on(flvjs.Events.METADATA_ARRIVED, () => {
    console.log('FLV 元数据已到达')
    loading.value = false
  })

  try {
    flvPlayer.value.load()
    // 延迟自动播放，等待数据加载
    setTimeout(() => {
      if (flvPlayer.value) {
        flvPlayer.value.play().catch(err => {
          console.warn('自动播放失败:', err)
          loading.value = false
        })
      }
    }, 500)
  } catch (err) {
    console.error('FLV 加载失败:', err)
    error.value = 'FLV 加载失败: ' + err.message
    loading.value = false
  }
}

const initHlsPlayer = () => {
  console.log('尝试使用 HLS 播放器')
  
  if (videoElement.value.canPlayType('application/vnd.apple.mpegurl')) {
    // Safari 原生支持 HLS
    console.log('使用原生 HLS 支持')
    videoElement.value.src = props.video.url
    videoElement.value.play().catch(err => {
      console.warn('原生 HLS 自动播放失败:', err)
      loading.value = false
    })
  } else if (Hls.isSupported()) {
    console.log('使用 HLS.js 播放器')
    hlsPlayer.value = new Hls({
      enableWorker: true,
      lowLatencyMode: false,
      backBufferLength: 90,
      maxBufferLength: 30,
      maxBufferSize: 60 * 1000 * 1000,
      maxBufferHole: 0.5
    })

    hlsPlayer.value.loadSource(props.video.url)
    hlsPlayer.value.attachMedia(videoElement.value)

    hlsPlayer.value.on(Hls.Events.MANIFEST_PARSED, () => {
      console.log('HLS manifest 解析完成')
      loading.value = false
      videoElement.value.play().catch(err => {
        console.warn('HLS 自动播放失败:', err)
      })
    })

    hlsPlayer.value.on(Hls.Events.ERROR, (event, data) => {
      console.error('HLS 错误:', data)
      if (data.fatal) {
        switch (data.type) {
          case Hls.ErrorTypes.NETWORK_ERROR:
            console.log('网络错误，尝试恢复...')
            error.value = '网络错误，正在重试...'
            setTimeout(() => hlsPlayer.value.startLoad(), 1000)
            break
          case Hls.ErrorTypes.MEDIA_ERROR:
            console.log('媒体错误，尝试恢复...')
            error.value = '媒体错误，正在重试...'
            hlsPlayer.value.recoverMediaError()
            break
          default:
            error.value = 'HLS 播放错误'
            loading.value = false
            isPlaying.value = false
            break
        }
      }
    })
  } else {
    error.value = '当前浏览器不支持 HLS 播放'
    loading.value = false
  }
}

const initNativePlayer = () => {
  console.log('使用原生播放器')
  videoElement.value.src = props.video.url
  videoElement.value.play().catch(err => {
    console.warn('原生播放器自动播放失败:', err)
    loading.value = false
  })
}

const handleVideoError = (e) => {
  console.error('视频错误事件:', e)
  const videoEl = videoElement.value
  if (videoEl) {
    const errorCode = videoEl.error ? videoEl.error.code : 'unknown'
    const errorMsg = videoEl.error ? videoEl.error.message : '未知错误'
    console.error('错误代码:', errorCode, '错误信息:', errorMsg)
    error.value = `视频错误 (${errorCode}): ${errorMsg}`
  } else {
    error.value = '视频加载失败'
  }
  loading.value = false
  isPlaying.value = false
}

const destroyPlayer = () => {
  if (loadTimeout) {
    clearTimeout(loadTimeout)
    loadTimeout = null
  }

  if (flvPlayer.value) {
    try {
      flvPlayer.value.pause()
      flvPlayer.value.unload()
      flvPlayer.value.detachMediaElement()
      flvPlayer.value.destroy()
    } catch (e) {
      console.error('销毁 FLV 播放器失败:', e)
    }
    flvPlayer.value = null
  }

  if (hlsPlayer.value) {
    try {
      hlsPlayer.value.destroy()
    } catch (e) {
      console.error('销毁 HLS 播放器失败:', e)
    }
    hlsPlayer.value = null
  }

  if (videoElement.value) {
    videoElement.value.pause()
    videoElement.value.src = ''
    videoElement.value.load()
  }
  
  isPlaying.value = false
}

onMounted(() => {
  // 延迟初始化，确保 DOM 完全加载
  setTimeout(() => {
    initPlayer()
  }, 100)
  
  // 监听全局停止事件
  window.addEventListener('stop-all-videos', handleGlobalStop)
})

onBeforeUnmount(() => {
  destroyPlayer()
  window.removeEventListener('stop-all-videos', handleGlobalStop)
})
</script>

<style scoped>
.video-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.video-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.card-header {
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.video-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.control-btn {
  background: #409eff;
  border: none;
  color: white;
  cursor: pointer;
  padding: 6px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s;
}

.control-btn svg {
  width: 18px;
  height: 18px;
}

.control-btn:hover {
  background: #66b1ff;
  transform: scale(1.05);
}

.control-btn:active {
  transform: scale(0.95);
}

.remove-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #909399;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s;
}

.remove-btn:hover {
  background: #f56c6c;
  color: white;
}

.video-container {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 比例 */
  background: #000;
}

.video-player {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.error-message,
.loading-message {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.85);
  color: white;
  padding: 20px;
  text-align: center;
  z-index: 10;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.error-message p {
  font-size: 14px;
  color: #f56c6c;
  margin-bottom: 15px;
}

.retry-btn {
  padding: 8px 20px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.retry-btn:hover {
  background: #66b1ff;
}

.loading-message p {
  font-size: 14px;
  margin-top: 10px;
  color: #409eff;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top-color: #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  cursor: pointer;
  transition: background 0.3s;
  z-index: 5;
}

.play-overlay:hover {
  background: rgba(0, 0, 0, 0.5);
}

.play-icon {
  width: 80px;
  height: 80px;
  background: rgba(64, 158, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.3s;
}

.play-overlay:hover .play-icon {
  transform: scale(1.1);
}

.play-icon svg {
  width: 40px;
  height: 40px;
  margin-left: 4px;
}

.card-footer {
  padding: 12px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.video-url {
  font-size: 12px;
  color: #909399;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.video-type {
  font-size: 11px;
  padding: 2px 8px;
  background: #409eff;
  color: white;
  border-radius: 3px;
  font-weight: 500;
  flex-shrink: 0;
}

.status-badge {
  font-size: 11px;
  padding: 2px 8px;
  border-radius: 3px;
  font-weight: 500;
  flex-shrink: 0;
}

.status-badge.playing {
  background: #67c23a;
  color: white;
}

.status-badge.loading {
  background: #e6a23c;
  color: white;
}

.status-badge.stopped {
  background: #909399;
  color: white;
}
</style>

